"""Asterisk Manager Interface for the Twisted networking framework

The Asterisk Manager Interface is a simple line-oriented protocol that allows
for basic control of the channels active on a given Asterisk server.

Module defines a standard Python logging module log 'AMI' 
"""
from twisted.internet import protocol, reactor, defer
from twisted.protocols import basic
from twisted.internet import error as tw_error
import socket, logging
from starpy import error
from starpy import manager

import logging

mylog = logging.getLogger( 'AmiEx' )

class AMIProtocolEx(manager.AMIProtocol):
    """ """
    def __init__( self, *args, **named ):
        """Initialise the AMIProtocol, arguments are ignored"""
        global g_log
        self.messageCache = []
        self.actionIDCallbacks = {}
        self.eventTypeCallbacks = {}
        self.hostName = socket.gethostname()

        manager.log.setLevel(logging.ERROR)
        mylog.setLevel(logging.ERROR)


class AMIFactory(protocol.ClientFactory):
    """A factory for AMI protocols
    """
    protocol = AMIProtocolEx

    def __init__(self, username, secret):
        self.username = username
        self.secret = secret
        
    def login( self, ip='localhost', port=5038, timeout=5 ):
        """Connect, returning our (singleton) protocol instance with login completed
        XXX This is messy, we'd much rather have the factory able to create
        large numbers of protocols simultaneously
        """
        self.loginDefer = defer.Deferred()
        reactor.connectTCP(ip, port, self, timeout=timeout)
        return self.loginDefer

    def clientConnectionFailed( self, connector, reason):
        """Connection failed, report to our callers"""
        self.loginDefer.errback( reason )
